import { Course } from '../../types/course'
import { execute, select } from '../../utils/db'
import { Page, PageReq } from '../../types/page'

export class CourseDao {
  /**
   * 创建课程
   */
  static async create(course: Omit<Course, 'id'>): Promise<number | undefined> {
    //默认未训练
    if(!course.train_status){
        course.train_status = 0
    }
    //根据course_time查询表course_time字段
    const result = await execute(
      'INSERT INTO course (course_time, train_doctor,course_date,train_status,process,total_time) VALUES (?, ?, ? ,?, ?,?) RETURNING id',
      [course.course_time, course.train_doctor,course.course_date,course.train_status,0,course.total_time]
    )
    return result?.lastInsertId
  }

  /**
   * 更新课程信息
   */
  static async update(id: number, course: Partial<Course>): Promise<void> {
    const fields = []
    const values = []

    if (course.course_time) {
      fields.push('course_time = ?')
      values.push(course.course_time)
    }
    if (course.train_doctor) {
      fields.push('train_doctor = ?')
      values.push(course.train_doctor)
    }
    if (course.train_status) {
      fields.push('train_status = ?')
      values.push(course.train_status)
    }
    if (course.start_time) {
      fields.push('start_time = ?')
      values.push(course.start_time)
    }
    if (course.end_time) {
      fields.push('end_time = ?')
      values.push(course.end_time)
    }
    if (course.process) {
      fields.push('process = ?')
      values.push(course.process)
    }
    if (course.total_time) {
      fields.push('total_time = ?')
      values.push(course.total_time)
    }

    if (fields.length === 0) return
    let sql = `UPDATE course SET ${fields.join(', ')} WHERE id = ?`
   // console.log('values',values)
   // console.log('sql',sql)
    await execute(
      sql,
      [...values, id]
    )
  }

  static async countCourse(train_status?:number,course_date?:string){
    const fields = []
    const values = []

    if (course_date) {
      fields.push('course_date = ?')
      values.push(course_date)
    }
    if (train_status) {
      fields.push('train_status = ?')
      values.push(train_status)
    }
    //console.log('fields',fields)
    if(fields.length > 0){
      const condition =  `WHERE ${fields.join(' AND ')}` 
      const result = await select(`SELECT COUNT(*) as count FROM course ${condition}`,values)
      return result[0].count
    }else{
      const result = await select(`SELECT COUNT(*) as count FROM course`)
      return result[0].count
    }
  }

  /**
   * 删除课程
   */
  static async delete(id: number): Promise<void> {
    await execute('DELETE FROM course WHERE id = ?', [id])
  }

  /**
   * 获取课程详情
   */
  static async getById(id: number): Promise<Course> {
    const result = await select<Course>(
      'SELECT * FROM course WHERE id = ? LIMIT 1',
      [id]
    )
    return result[0]
  }

  /**
   * 获取课程列表
   */
  static async list(): Promise<Course[]> {
    const result = await select<Course[]>('SELECT * FROM course')
    return result
  }

  /**
   * 分页查询课程列表
   */
  static async page(params: PageReq<Course>): Promise<Page<Course>> {
    const { pageNum, pageSize } = params
    const offset = (pageNum - 1) * pageSize
    const fields = []
    const values = []
    const course = params.params
    
    if (course.course_time) {
      fields.push('course_time = ?')
      values.push(course.course_time)
    }
    if (course.train_doctor) {
      fields.push('train_doctor = ?')
      values.push(course.train_doctor)
    }

    const condition = fields.length > 0 ? `WHERE 1=1 ${fields.join(' AND ')}` : ''
    const [totalResult, listResult] = await Promise.all([
      select('SELECT COUNT(*) as count FROM course ' + condition, values),
      select(`SELECT * FROM course ${condition} LIMIT ${pageSize} OFFSET ${offset}`, values)
    ])

    return {
      total: totalResult[0].count || 0,
      list: (listResult as unknown as Course[]) || []
    }
  }
}